<?php
include_once('config/config.php');
$auth = check_auth();
include_once('./config/logout.php');

if($_POST)
{
    // 接收参数
    $name = trim($_POST['name']) ?? '';
    $mobile = trim($_POST['mobile']) ?? '';
    $email = trim($_POST['email']) ?? '';
    $gender = trim($_POST['gender']) ?? '';
    $address = trim($_POST['address']) ?? '';
    $depid = trim($_POST['depid']) ?? '';
    $jobid = trim($_POST['jobid']) ?? '';
    $code = trim($_POST['code']) ?? '';
	// var_dump($code);
	// exit;
    if(empty($name))
    {
        showMsg('姓名不能为空');
    }

    if(empty($mobile))
    {
        showMsg('手机号不能为空');
    }

    // 判断手机号格式是否正确
    $mobileReg = '/^1[3456789]\d{9}$/';

    preg_match($mobileReg,$mobile,$mobileResult);

    if(empty($mobileResult))
    {
        showMsg('手机号格式错误');
    }

    if(empty($email))
    {
        showMsg('邮箱不能为空');
    }

    if(empty($address))
    {
        showMsg('地址不能为空');
    }

    $mobileSql = "SELECT * FROM `pre_person` WHERE `mobile` = '$mobile'";

    $mobileInfo = find($mobileSql);

    if($mobileInfo)
    {
        showMsg('手机号已存在');
    }

    $emailSql = "SELECT * FROM `pre_person` WHERE `email` = '$email'";

    $emailInfo = find($emailSql);

    if($emailInfo)
    {
        showMsg('邮箱已存在');
    }

    // 查询部门是否存在
    $depSql = "SELECT * FROM `pre_dep` WHERE `id` = '$depid'";

    $depInfo = find($depSql);

    if(!$depInfo)
    {
        showMsg('部门不存在');
    }

    // 查询职位
    $jobSql = "SELECT * FROM `pre_job` WHERE `id` = '$jobid'";

    $jobInfo = find($jobSql);

    if(!$jobInfo)
    {
        showMsg('职位不存在');
    }

    $data = [
        'name' => $name,
        'mobile' => $mobile,
        'email' => $email,
        'gender' => $gender,
        'address' => $address,
        'depid' => $depid,
        'jobid' => $jobid,
        'createtime' => time()
    ];

    // 处理地区数据
    $regionSql = "SELECT `parentpath` FROM `pre_region` WHERE `code` = '$code'";

    $parentpath = find($regionSql);

    if(empty($parentpath))
    {
        showMsg('所选地区不存在');
    }

    $pathArr = explode(',',$parentpath['parentpath']);

    $data['province'] = $pathArr[0] ?? '';
    $data['city'] = $pathArr[1] ?? '';
    $data['district'] = $pathArr[2] ?? '';

    // 头像
    $res = build_upload('avatar');

    if($res['code'] === 0)
    {
        showMsg($res['msg']);
    }

    $data['avatar'] = $res['data'];


    // 插入数据表
    $result = add('person',$data);

    if($result['code'] === 1)
    {
        showMsg('添加员工成功','personList.php');
    }else{
        // 判断是否常规文件 如果是的就删除文件
        @is_file('.' . $data['avatar']) && @unlink('.' . $data['avatar']);

        echo $result['data'];
        exit;
    }
}

$DepSql = "SELECT * FROM `pre_dep` ORDER BY `id` DESC";

$DepData = finds($DepSql);
// var_dump($DepData);
// exit;
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <?php include_once('common/meta.php'); ?>
    <link rel="stylesheet" href="./assets/lib/city-picker/city-picker.css">
</head>

<body>

    <?php include_once('common/header.php'); ?>

    <?php include_once('common/menu.php'); ?>

    <div class="content">
        <div class="header">
            <h1 class="page-title">添加员工</h1>
        </div>
        <ul class="breadcrumb">
            <li><a href="index.php">Home</a> <span class="divider">/</span></li>
            <li class="active">Index</li>
        </ul>

        <div class="container-fluid">
            <div class="row-fluid">

                <div class="btn-toolbar">
                    <button class="btn btn-primary" onClick="location='personList.php'"><i class="icon-list"></i> 员工列表</button>
                    <div class="btn-group">
                    </div>
                </div>

                <div class="well">
                    <div id="myTabContent" class="tab-content">
                        <div class="tab-pane active in" id="home">
                            <form method="post" enctype="multipart/form-data">
                                
                                <label>姓名</label>
                                <input type="text" name="name" class="input-xxlarge">

                                <label>手机号</label>
                                <input type="text" name="mobile" class="input-xxlarge">
                                
                                <label>邮箱</label>
                                <input type="email" name="email" class="input-xxlarge">

                                <label>性别</label>
                                <select name="gender" class="input-xlarge">
                                    <option value="0">保密</option>
                                    <option value="1">男</option>
                                    <option value="2">女</option>
                                </select>

                                <div class="input-xlarge" style="position: relative;height:60px;margin-bottom:5px;">
								<label>地区</label>
                                    <input type="text" id="region" readonly data-toggle="city-picker" class="input-xxlarge">
                                    <input type="hidden" name="code" id="code">
                                </div>
                                
                                <label>地址</label>
                                <input type="text" name="address" class="input-xxlarge">
                                
                                <label>部门</label>
                                <select name="depid" class="input-xlarge">
                                    <option value="0">请选择</option>
                                    <?php foreach($DepData as $item){ ?>
                                        <option value="<?php echo $item['id']; ?>"><?php echo $item['name']; ?></option>
                                    <?php }?>
                                </select>

                                <label>职位</label>
                                <select name="jobid" class="input-xlarge">
                                    <option value="0">请选择</option>
                                </select>

                                <label>头像</label>
                                <img style="width: 200px;height: 200px;" id="upload" src="/assets/images/avatar.png" alt="">
                                <input type="file" hidden name="avatar" id="avatar">

                                <label></label>
                                <input class="btn btn-primary" type="submit" value="提交" />
                            </form>
                        </div>
                    </div>
                </div>

                <?php include_once('common/footer.php'); ?>

            </div>
        </div>
    </div>

</body>

</html>
<?php include_once('common/script.php'); ?>
<script src="./assets/lib/city-picker/city-picker.data.min.js"></script>
<script src="./assets/lib/city-picker/city-picker.min.js"></script>

<script>
    // 模拟点击上传框
    $('#upload').click(function(){
        $('#avatar').click();
    });

    // 监听上传框的值是否有变化
    $('#avatar').change(function(){
        let file = $(this)[0].files[0];

        if(file)
        {
            let Reader = new FileReader();

            Reader.readAsDataURL(file);

            Reader.onload = function()
            {
                $('#upload').attr('src',Reader.result);
            }
        }
    });

    // 当选择部门后触发查询该部门的相应职位
    $('select[name="depid"]').change(function(){
        // 获取部门id
        let depid = $(this).val();

        $.ajax({
            type:'post',
            url:'api.php',
            data:{
                depid,
                action:'get_job',
            },
            dataType:'json',
            success:function(res)
            {
                let tmp = '';

                if(res && res.code === 1)
                {
                    for(let item of res.data)
                    {
                        tmp += `<option value="${item.id}">${item.name}</option>`
                    }
                    
                }else{
                    tmp = `<option value="0">${res.msg}</option>`
                }

                $('select[name="jobid"]').html(tmp);
            }
        });
    });
	$("#region").on("cp:updated", function() {
        var citypicker = $(this).data("citypicker");
        var code = citypicker.getCode("district") || citypicker.getCode("city") || citypicker.getCode("province");
        $("#code").val(code);
    });

</script>
